﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SQLite;
using System.Security.Permissions;
using Android.Preferences;
using Android.Graphics.Drawables;
using Android.Views.Animations;
using Android.Content.PM;

namespace WisdriContactsAndroid
{
    [Activity(Label = "更新")]
    public class Update : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Create your application here
            SetContentView(Resource.Layout.Update);


            var buttonUpdate = FindViewById<Button>(Resource.Id.buttonUpdate);
            var textViewCurrentVersion = FindViewById<TextView>(Resource.Id.textViewCurrentVersion);
            var textViewLatestVersion = FindViewById<TextView>(Resource.Id.textViewLatestVersion);
            var progressBarUpdate = FindViewById<ProgressBar>(Resource.Id.progressBarUpdate);
            var buttonAppUpdate = FindViewById<Button>(Resource.Id.buttonAppUpdate);
            var textViewCurrentAppVersion = FindViewById<TextView>(Resource.Id.textViewCurrentAppVersion);
            var textViewLatestAppVersion = FindViewById<TextView>(Resource.Id.textViewLatestAppVersion);

            progressBarUpdate.Visibility = ViewStates.Invisible;

            var preference = GetSharedPreferences("settings", FileCreationMode.WorldWriteable);
            var editor = preference.Edit();
            if (!preference.Contains("version"))
            {
                editor.PutString("version", "20150504");
                editor.Commit();
            }
            textViewCurrentVersion.Text = preference.GetString("version", "20150504");

            editor.PutString("appVersion", PackageManager.GetPackageInfo(PackageName, 0).VersionName);
            editor.Commit();

            textViewCurrentAppVersion.Text = preference.GetString("appVersion", "0");

            buttonUpdate.Click += async (sender, e) =>
            {
                try
                {
                    buttonUpdate.Enabled = false;
                    buttonUpdate.Text = "正在更新";

                    var requestVersion = WebRequest.Create("http://kidfruit.github.io/WisdriContacts/LatestDataVersion.txt?" + Guid.NewGuid().ToString());

                    requestVersion.Method = "GET";
                    using (var response = await requestVersion.GetResponseAsync())
                    {
                        using (var responseStream = response.GetResponseStream())
                        {
                            using (var sr = new StreamReader(responseStream, Encoding.UTF8))
                            {
                                var receive = sr.ReadToEnd();

                                textViewLatestVersion.Text = receive;
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(textViewLatestVersion.Text.Trim()) &&
                        textViewCurrentVersion.Text != textViewLatestVersion.Text)
                    {

                        progressBarUpdate.Visibility = ViewStates.Visible;

                        var request = WebRequest.Create("http://kidfruit.github.io/WisdriContacts/data.txt?" + Guid.NewGuid().ToString());
                        request.Method = "GET";
                        using (var response = await request.GetResponseAsync())
                        {
                            using (var responseStream = response.GetResponseStream())
                            {
                                using (var sr = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8")))
                                {

                                    int count = 0;
                                    long length = responseStream.Length;
                                    byte[] receiveStream = new byte[length];
                                    progressBarUpdate.Visibility = ViewStates.Visible;
                                    progressBarUpdate.Indeterminate = false;
                                    progressBarUpdate.Max = (int)length;
                                    progressBarUpdate.Progress = 0;

                                    while (true)
                                    {
                                        int readLength = (int)(length - count > 1000 ? 1000 : length - count);
                                        int num = await responseStream.ReadAsync(receiveStream, count, readLength);
                                        if (num == 0)
                                            break;

                                        count += num;
                                        progressBarUpdate.Progress = count;
                                    }

                                    var receive = Encoding.UTF8.GetString(receiveStream, 0, (int)length);


                                    //var receive = await sr.ReadToEndAsync();

                                    var byteValue = Convert.FromBase64String(receive);
                                    string decodeReceive = Encoding.UTF8.GetString(byteValue, 0, byteValue.Length);

                                    var personList = JsonConvert.DeserializeObject<List<PERSON>>(decodeReceive);

                                    var dbFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "contacts.db");
                                    using (SQLiteConnection conn = new SQLiteConnection(dbFile))
                                    {
                                        try
                                        {
                                            var sql = "delete from PERSON";
                                            int oldDataCount = conn.Execute(sql);
                                            new AlertDialog.Builder(this).SetMessage(string.Format("旧数据有{0}条", oldDataCount)).Show();

                                            sql = "DROP TABLE [PERSON];";
                                            conn.Execute(sql);
                                            sql = @"CREATE TABLE [PERSON] (
                                          [ID] nvarchar(2147483647) NOT NULL
                                        , [NAME] nvarchar(2147483647) NULL
                                        , [DEPARTMENT] nvarchar(2147483647) NULL
                                        , [MOBILE_PHONE] nvarchar(2147483647) NULL
                                        , [VIRTUAL_PHONE] nvarchar(2147483647) NULL
                                        , [POSITION] nvarchar(2147483647) NULL
                                        , [REGION] nvarchar(2147483647) NULL
                                        , [OFFICE_PHONE] nvarchar(2147483647) NULL
                                        , [INNER_PHONE] nvarchar(2147483647) NULL
                                        , [PY] nvarchar(2147483647) NULL
                                        , [CAR] nvarchar(2147483647) NULL
                                        , CONSTRAINT [sqlite_autoindex_PERSON_1] PRIMARY KEY ([ID])
                                        );";
                                            conn.Execute(sql);


                                            conn.BeginTransaction();
                                            conn.InsertAll(personList);

                                            textViewCurrentVersion.Text = textViewLatestVersion.Text;
                                            editor.PutString("version", textViewCurrentVersion.Text);
                                            editor.Commit();

                                            sql = "select count(ID) from PERSON";
                                            int newDataCount = conn.ExecuteScalar<int>(sql);
                                            new AlertDialog.Builder(this).SetMessage(string.Format("新数据有{0}条", newDataCount)).Show();

                                            conn.Commit();

                                            new AlertDialog.Builder(this).SetMessage("更新完毕").SetPositiveButton("确定", delegate
                                                {
                                                }).Show();


                                        }
                                        catch (Exception ex)
                                        {
                                            conn.Rollback();
                                            new AlertDialog.Builder(this).SetMessage(ex.Message).Show();
                                        }
                                    }
                                }
                            }
                        }

                    }
                    else
                    {
                        new AlertDialog.Builder(this).SetMessage("无需更新").Show();
                    }

                }
                catch (System.Exception ex)
                {
                    new AlertDialog.Builder(this).SetMessage(ex.Message).Show();
                }
                finally
                {
                    progressBarUpdate.Visibility = ViewStates.Invisible;
                    buttonUpdate.Enabled = true;
                    buttonUpdate.Text = "更新数据";
                }
            };

            buttonAppUpdate.Click += async (sender, e) =>
            {
                try
                {
                    buttonAppUpdate.Enabled = false;
                    var requestAppVersion = WebRequest.Create("http://kidfruit.github.io/WisdriContacts/LatestAndroidVersion.txt?" + Guid.NewGuid().ToString());

                    requestAppVersion.Method = "GET";
                    using (var response = await requestAppVersion.GetResponseAsync())
                    {
                        using (var responseStream = response.GetResponseStream())
                        {
                            using (var sr = new StreamReader(responseStream, Encoding.UTF8))
                            {
                                var receive = sr.ReadToEnd();

                                textViewLatestAppVersion.Text = receive;
                            }
                        }
                    }

                    buttonAppUpdate.Enabled = true;

                    if (!string.IsNullOrEmpty(textViewLatestAppVersion.Text.Trim()) &&
                        textViewCurrentAppVersion.Text != textViewLatestAppVersion.Text)
                    {
                        var uri = Android.Net.Uri.Parse("http://pan.baidu.com/s/1ntypvj7");
                        var intent = new Intent(Intent.ActionView, uri);
                        StartActivity(intent);

                        new AlertDialog.Builder(this).SetMessage("下载更新包").Show();
                    }
                    else
                    {
                        new AlertDialog.Builder(this).SetMessage("无需更新").Show();
                    }
                }
                catch (System.Exception ex)
                {
                    new AlertDialog.Builder(this).SetMessage(ex.Message).Show();
                }
                finally
                {
                    progressBarUpdate.Visibility = ViewStates.Invisible;
                }
            };
        }
    }
}

